<?php

namespace App\Console\Commands;

use App\Http\Services\Om\InventoryService;
use App\Http\Services\Op\LendService;
use App\Http\Services\Produce\ProcessingService;
use App\Http\Services\Produce\QCheckService;
use App\Http\Services\Produce\WCheckService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class exportData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:exportData {--type=} {--id=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '数据导出到excel缓存文件';

    protected $_cellName = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $type = $this->option('type') ?: "";
        $id = $this->option('id') ?: "";
        if(empty($type) || empty($id)){
            dd("参数缺少");
        }
        switch ($type){
            //库存分配
            case "inventory":
                $this->inventory($id);
                break;
            //全员借赠还
            case "lend":
                $this->lends($id);
                break;
            //生产加工单
            case "processing":
                $this->processing($id);
                break;
            //qc质检
            case "qcCheck":
                $this->qcCheck($id);
                break;
            //wc仓检
            case "wcCheck":
                $this->wcCheck($id);
                break;
            default:
                dd("未找到导出任务类型");
        }
    }

    //仓检
    public function wcCheck($id)
    {
        //获取导出的任务进度
        $processKey = "WCCHECK_EXCEL_EXPORT_{$id}";
        $cache = Cache::get($processKey);
        if(empty($cache)){
            dd("无导出任务");
        }
        $file = storage_path("cache/wcCheck/").$cache['file'];
        // 如果需要打开一个空的Excel文件进行写入，可以使用IOFactory来加载文件
        $spreadsheet = IOFactory::load($file);
        // 获取活动的工作表
        $sheet = $spreadsheet->getActiveSheet();
        $param = array_merge(['page' => 1, 'limit' => 20], $cache['param']);
        $header = [
            ['qc_user', 'qc质检员'],
            ['type_no', '款名'],
            ['number', 'RFID编码'],
            ['factory_name', '工厂名称'],
            ['qc_time', '验货期'],
            ['status', 'qc质检结果'],
            ['qc_img', '图片']
        ];
        foreach($header as $index => $item){
            $sheet->setCellValue($this->_cellName[$index]."1", $item[1]);
            $sheet->getStyle($this->_cellName[$index]."1")->applyFromArray([
                'fill' => [
                    'fillType' => Fill::FILL_SOLID,
                    'startColor' => [
                        'argb' => Color::COLOR_BLACK,
                    ],
                ],
                'font' => [
                    'color' => [
                        'argb' => Color::COLOR_WHITE,
                    ],
                ]
            ]);
            $sheet->getColumnDimension($this->_cellName[$index])->setWidth('20');
        }
        $total = 1;
        $num = 2;
        for($page=1;$page<=$total;$page++){
            $param['page'] = $page;
            $res = (new WCheckService())->search($param);
            if($page == 1){
                $total = $res['total'] ?? 1;
            }
            if(empty($res['data'])){
                break;
            }
            foreach ($res['data'] as $item){
                $data = [
                    'qc_user' => $item['qc_user'],
                    'type_no' => $item['type_no'],
                    'number' => $item['number'],
                    'factory_name' => $item['factory_name'],
                    'qc_time' => $item['qc_time'],
                    'status' => $item['status'] == 1 ? "合格" : "不合格",
                    'qc_img' => $item['qc_img'] ?: "",
                ];
                foreach ($header as $index => $hItem){
                    $sheet->setCellValue($this->_cellName[$index].$num, $data[$hItem[0]]);
                }
                $num++;
            }
            //计算当前下载进度
            $process = round($num/$total*100, 2);
            $cache['process'] = $process >= 100 ? 99.99 : $process;
            Cache::put($processKey, $cache, (new Carbon())->now()->addSeconds(60));
        }
        // 保存Excel文件
        (new Xlsx($spreadsheet))->save($file);
        Cache::forget($processKey);
        dd("数据下载完成！！！");
    }

    //qc质检
    public function qcCheck($id)
    {
        //获取导出的任务进度
        $processKey = "QCCHECK_EXCEL_EXPORT_{$id}";
        $cache = Cache::get($processKey);
        if(empty($cache)){
            dd("无导出任务");
        }
        $file = storage_path("cache/qcCheck/").$cache['file'];
        // 如果需要打开一个空的Excel文件进行写入，可以使用IOFactory来加载文件
        $spreadsheet = IOFactory::load($file);
        // 获取活动的工作表
        $sheet = $spreadsheet->getActiveSheet();
        $param = array_merge(['page' => 1, 'limit' => 20], $cache['param']);
        $header = [
            ['qc_user', 'qc质检员'],
            ['type_no', '款名'],
            ['number', 'RFID编码'],
            ['factory_name', '工厂名称'],
            ['qc_time', '验货期'],
            ['status', 'qc质检结果'],
            ['qc_img', '图片']
        ];
        foreach($header as $index => $item){
            $sheet->setCellValue($this->_cellName[$index]."1", $item[1]);
            $sheet->getStyle($this->_cellName[$index]."1")->applyFromArray([
                'fill' => [
                    'fillType' => Fill::FILL_SOLID,
                    'startColor' => [
                        'argb' => Color::COLOR_BLACK,
                    ],
                ],
                'font' => [
                    'color' => [
                        'argb' => Color::COLOR_WHITE,
                    ],
                ]
            ]);
            $sheet->getColumnDimension($this->_cellName[$index])->setWidth('20');
        }
        $total = 1;
        $num = 2;
        for($page=1;$page<=$total;$page++){
            $param['page'] = $page;
            $res = (new QCheckService())->search($param);
            if($page == 1){
                $total = $res['total'] ?? 1;
            }
            if(empty($res['data'])){
                break;
            }
            foreach ($res['data'] as $item){
                $data = [
                    'qc_user' => $item['qc_user'],
                    'type_no' => $item['type_no'],
                    'number' => $item['number'],
                    'factory_name' => $item['factory_name'],
                    'qc_time' => $item['qc_time'],
                    'status' => $item['status'] == 1 ? "合格" : "不合格",
                    'qc_img' => $item['qc_img'] ?: "",
                ];
                foreach ($header as $index => $hItem){
                    $sheet->setCellValue($this->_cellName[$index].$num, $data[$hItem[0]]);
                }
                $num++;
            }
            //计算当前下载进度
            $process = round($num/$total*100, 2);
            $cache['process'] = $process >= 100 ? 99.99 : $process;
            Cache::put($processKey, $cache, (new Carbon())->now()->addSeconds(60));
        }
        // 保存Excel文件
        (new Xlsx($spreadsheet))->save($file);
        Cache::forget($processKey);
        dd("数据下载完成！！！");
    }

    //全员借赠还
    public function lends($id)
    {
        //获取导出的任务进度
        $processKey = "LEND_EXCEL_EXPORT_{$id}";
        $cache = Cache::get($processKey);
        if(empty($cache)){
            dd("无导出任务");
        }
        $file = storage_path("cache/allocation/").$cache['file'];
        // 如果需要打开一个空的Excel文件进行写入，可以使用IOFactory来加载文件
        $spreadsheet = IOFactory::load($file);
        // 获取活动的工作表
        $sheet = $spreadsheet->getActiveSheet();
        $param = array_merge(['page' => 1, 'limit' => 20], $cache['param']);
        $header = [
            ['allocation_number','单号'],
            ['adduser','发起人'],
            ['groups','单据类型'],
            ['total_num','单据申请数/实际数'],
            ['actually_return_num','已归还数'],
            ['ipurchase_num','转内购数'],
            ['give_num','转赠送数'],
            ['sale_num','转销售数'],
            ['sku_code','sku编码'],
            ['type_name','款名'],
            ['sku_num','sku申请数/实际数'],
            ['sku_return_num', 'sku归还数'],
            ['sku_ipurchase_num', 'sku转内购数'],
            ['sku_give_num', 'sku转赠送数'],
            ['sku_sale_num', 'sku转销售数'],
            ['is_return','sku归还状态'],
            ['status','调拨状态'],
            ['reason','申请事由'],
            ['remark','备注'],
            ['data_return','单据归还状态'],
            ['data_status','单据状态'],
            ['createtime','发起时间'],
            ['source_allocation_number','来源单号'],
            ['is_subject', '主体']
        ];
        foreach($header as $index => $item){
            $sheet->setCellValue($this->_cellName[$index]."1", $item[1]);
            $sheet->getStyle($this->_cellName[$index]."1")->applyFromArray([
                'fill' => [
                    'fillType' => Fill::FILL_SOLID,
                    'startColor' => [
                        'argb' => Color::COLOR_BLACK,
                    ],
                ],
                'font' => [
                    'color' => [
                        'argb' => Color::COLOR_WHITE,
                    ],
                ]
            ]);
            $sheet->getColumnDimension($this->_cellName[$index])->setWidth('20');
        }
        $isSubjects = ["kz" => "十三余", "yx" => "有香", "mz" => "妙哉", 'xm' => "一弦一木", 'js' => '锦瑟'];
        $statusMap = [-1 => '未发起', 0 => '审核中', 1 => '已通过', 2 => '已拒绝', 3 => '已撤回', 4 => '已撤销'];
        $groupsMap = [1 => "赠送", 2 => "借出", 3 => "归还", 4 => "销售"];
        $total = 1;
        $currentRow = 1;
        $num = 2;
        for($page = 1; $page <= $total; $page++) {
            $param['page'] = $page;
            $res = (new LendService())->search($param);
            if ($page == 1) {
                $total = $res['total'] ?? 1;
            }
            if (empty($res['data'])) {
                break;
            }
            foreach ($res['data'] as $item){
                $detailList = [];
                if($item['groups'] == 1){
                    $detailList = (new LendService())->giveList($item['allocation_number']);
                }else if(in_array($item['groups'], [2, 4])){
                    $detailList = (new LendService())->lendList($item['allocation_number']);
                }else if($item['groups'] == 3){
                    $detailList = (new LendService())->returnList($item['allocation_number'], 3);
                }
                foreach ($detailList as $detail){
                    $data = [
                        'allocation_number' => $item['allocation_number'],
                        'adduser' => $item['adduser'],
                        'groups' => $groupsMap[$item['groups']] ?? $item['groups'],
                        'total_num' => $item['plan_num']."/".$item['actually_num'],
                        'actually_return_num' => $item['actually_return_num'],
                        'ipurchase_num' => $item['ipurchase_num'],
                        'give_num' => $item['give_num'],
                        'sale_num' => $item['sale_num'],
                        'sku_code' => $detail['sku_code'],
                        'type_name' => $detail['type_name'],
                        'sku_num' => $detail['num']."/". ($detail['actually_num'] ?? 0),
                        'sku_return_num' => $item['groups'] == 3 ? $detail['actually_num'] : $detail['actually_return_num'],//归还的实际调拨数就是 实际归还数
                        'sku_ipurchase_num' => $detail['ipurchase_num'] ?? 0,
                        'sku_give_num' => $detail['give_num'] ?? 0,
                        'sku_sale_num' => $detail['sale_num'] ?? 0,
                        'status' => $statusMap[$item['status']] ?? $item['status'],
                        'is_return' => $detail['is_return'] == 0 ? "未归还" : ($detail['is_return'] == 1 ? "部分归还" : "全部归还"),
                        'reason' => $item['reason'],
                        'remark' => $item['remark'],
                        'data_return' => $item['data_return'] == 0 ? "未归还" : ($item['data_return'] == 1 ? "部分归还" : "全部归还"),
                        'data_status' => $item['data_status'] == 0 ? "进行中" : "已完结",
                        'createtime' => $item['createtime'],
                        'is_subject' => $isSubjects[$item['is_subject']] ?? $item['is_subject'],
                        'source_allocation_number' => $item['source_allocation_number'] ?: ""
                    ];
                    foreach ($header as $index => $hItem){
                        $sheet->setCellValue($this->_cellName[$index].$num, $data[$hItem[0]]);
                    }
                    $num++;
                }
                $currentRow++;
                //计算当前下载进度
                $process = round($currentRow/$total*100, 2);
                $cache['process'] = $process >= 100 ? 99.99 : $process;
                Cache::put($processKey, $cache, (new Carbon())->now()->addSeconds(60));
            }
        }
        // 保存Excel文件
        (new Xlsx($spreadsheet))->save($file);
        Cache::forget($processKey);
        dd("数据下载完成！！！");
    }

    //库存分配
    public function inventory($id)
    {
        //获取导出的任务进度
        $processKey = "INVENTORY_EXCEL_EXPORT_{$id}";
        $cache = Cache::get($processKey);
        if(empty($cache)){
            dd("无导出任务");
        }
        $file = storage_path("cache/inventory/").$cache['file'];
        // 如果需要打开一个空的Excel文件进行写入，可以使用IOFactory来加载文件
        $spreadsheet = IOFactory::load($file);
        // 获取活动的工作表
        $sheet = $spreadsheet->getActiveSheet();
        $param = array_merge(['page' => 1, 'limit' => 20], $cache['param']);
        $header = [
            ['type_no', '商品编码'],
            ['product_code', '规格编码'],
            ['product_name', '款名'],
            ['a_parts', '部件'],
            ['tbnum', '预售/现货'],
            ['tmnum', '预售/现货'],
            ['dynum', '预售/现货'],
            ['liunum', '留存'],
            ['count', '总数'],
            ['countsss', '预售总数/现货总数'],
            ['arrivaldate', '预计到货日期'],
            ['arrivaldate_title', '预计到货天数']
        ];
        foreach($header as $index => $item){
            $sheet->setCellValue($this->_cellName[$index]."1", $item[1]);
            $sheet->getStyle($this->_cellName[$index]."1")->applyFromArray([
                'fill' => [
                    'fillType' => Fill::FILL_SOLID,
                    'startColor' => [
                        'argb' => Color::COLOR_BLACK,
                    ],
                ],
                'font' => [
                    'color' => [
                        'argb' => Color::COLOR_WHITE,
                    ],
                ]
            ]);
            $sheet->getColumnDimension($this->_cellName[$index])->setWidth('20');
        }
        $total = 1;
        $num = 2;
        for($page=1;$page<=$total;$page++){
            $param['page'] = $page;
            $res = (new InventoryService())->search($param);
            if($page == 1){
                $total = $res['total'] ?? 1;
            }
            if(empty($res['data'])){
                break;
            }
            foreach ($res['data'] as $item){
                $data = [
                    'type_no' => $item['type_no'],
                    'product_code' => $item['product_code'],
                    'product_name' => $item['product_name'],
                    'a_parts' => $item['a_parts'],
                    'tbnum' => $item['tb']['yushou']."/".$item['tb']['xianhu'],
                    'tmnum' => $item['tm']['yushou']."/".$item['tm']['xianhu'],
                    'dynum' => $item['dy']['yushou']."/".$item['dy']['xianhu'],
                    'liunum' => $item['liu']['yuliu'],
                    'count' => $item['count'],
                    'countsss' => $item['yushou']."/".$item['xianhu'],
                    'arrivaldate' => $item['arrivaldate'],
                    'arrivaldate_title' => $item['arrivaldate_title']
                ];
                foreach ($header as $index => $hItem){
                    $sheet->setCellValue($this->_cellName[$index].$num, $data[$hItem[0]]);
                }
                $num++;
            }
            //计算当前下载进度
            $process = round($num/$total*100, 2);
            $cache['process'] = $process >= 100 ? 99.99 : $process;
            Cache::put($processKey, $cache, (new Carbon())->now()->addSeconds(60));
        }
        // 保存Excel文件
        (new Xlsx($spreadsheet))->save($file);
        Cache::forget($processKey);
        dd("数据下载完成！！！");
    }

    //生产加工单
    public function processing($id)
    {
        //获取导出的任务进度
        $processKey = "PROCESSING_EXCEL_EXPORT_{$id}";
        $cache = Cache::get($processKey);
        if(empty($cache)){
            dd("无导出任务");
        }
        $file = storage_path("cache/processing/").$cache['file'];
        // 如果需要打开一个空的Excel文件进行写入，可以使用IOFactory来加载文件
        $spreadsheet = IOFactory::load($file);
        // 获取活动的工作表
        $sheet = $spreadsheet->getActiveSheet();
        $param = array_merge(['page' => 1, 'limit' => 20], $cache['param']);
        $header = [
            ['processing_code', '加工单号'],
            ['f_status', '完结状态'],
            ['sku_code', 'SKU'],
            ['num', '下单数'],
            ['zc_num', '增裁数'],
            ['bao_number', '报次数'],
            ['yc_num', '溢装比数'],
            ['qty', '入库数'],
            ['not_in_num', '未入库数'],
            ['factory_contract_no', '合同号'],
            ['factory_name', '供应商'],
            ['verify_price_number', '大货核价编码'],
            ['countprice', '总价'],
            ['embroidery_factory', '绣花厂'],
            ['embroidery_price', '绣花厂单价'],
            ['contract_date', '合同交期'],
            ['batch_date', '批次'],
            ['order_processor', '理单人'],
            ['add_date', '客人下单日期']
        ];
        foreach($header as $index => $item){
            $sheet->setCellValue($this->_cellName[$index]."1", $item[1]);
            $sheet->getStyle($this->_cellName[$index]."1")->applyFromArray([
                'fill' => [
                    'fillType' => Fill::FILL_SOLID,
                    'startColor' => [
                        'argb' => Color::COLOR_BLACK,
                    ],
                ],
                'font' => [
                    'color' => [
                        'argb' => Color::COLOR_WHITE,
                    ],
                ]
            ]);
            $sheet->getColumnDimension($this->_cellName[$index])->setWidth('20');
        }
        $total = 1;
        $num = 2;
        for($page=1;$page<=$total;$page++){
            $param['page'] = $page;
            $res = (new ProcessingService())->search($param);
            if($page == 1){
                $total = $res['total'] ?? 1;
            }
            if(empty($res['data'])){
                break;
            }
            foreach ($res['data'] as $item){
                $data = [
                    'processing_code' => $item['processing_code'],
                    'f_status' => $item['f_status'] == 0 ? "进行" : "完结",
                    'sku_code' => $item['sku_code'],
                    'num' => $item['num'],
                    'zc_num' => $item['zc_num'],
                    'bao_number' => $item['bao_number'],
                    'yc_num' => $item['yc_num'],
                    'qty' => $item['qty'],
                    'not_in_num' => $item['not_in_num'],
                    'factory_contract_no' => $item['factory_contract_no'],
                    'factory_name' => $item['factory_name'],
                    'verify_price_number' => $item['verify_price_number'],
                    'countprice' => $item['countprice'],
                    'embroidery_factory' => $item['embroidery_factory'],
                    'embroidery_price' => $item['embroidery_price'],
                    'order_processor' => $item['order_processor'],
                    'add_date' => $item['add_date'],
                    'contract_date' => $item['contract_date'],
                    'batch_date' => $item['batch_date']
                ];
                foreach ($header as $index => $hItem){
                    $sheet->setCellValue($this->_cellName[$index].$num, $data[$hItem[0]]);
                }
                $num++;
            }
            //计算当前下载进度
            $process = round($num/$total*100, 2);
            $cache['process'] = $process >= 100 ? 99.99 : $process;
            Cache::put($processKey, $cache, (new Carbon())->now()->addSeconds(60));
        }
        // 保存Excel文件
        (new Xlsx($spreadsheet))->save($file);
        Cache::forget($processKey);
        dd("数据下载完成！！！");
    }
}
